package com.xdap.init.dao;

import com.definesys.mpaas.query.MpaasQuery;
import com.xdap.init.pojo.po.DataModelField;
import com.xdap.motor.utils.StringUtils;
import com.xdap.runtime.service.RuntimeDatasourceService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @USER liShuShu
 * @TIME 2023/2/13 0013 16:49
 * @DESC 查询客户表
 **/
@Repository
@RequiredArgsConstructor
public class ModelFeildDao {
    private final RuntimeDatasourceService runtimeDatasourceService;

    @Value("${spring.datasource.name}")
    private String tenantSchema;

    public List<DataModelField> getFields(String TableName) {
        if (TableName == null || StringUtils.isBlank(TableName + "")) {
            return null;
        }
        MpaasQuery mpaasQuery = runtimeDatasourceService.buildTenantMpaasQuery(tenantSchema);
        mpaasQuery.eq("model_code", TableName);
        mpaasQuery.table("apaas_data_model_field");
        List<DataModelField> apaasDataModelFields = mpaasQuery.doQuery(DataModelField.class);
        return apaasDataModelFields;
    }


    public void updateField(DataModelField field) {
        if (field == null) {
            return;
        }
        MpaasQuery mpaasQuery = runtimeDatasourceService.buildTenantMpaasQuery(tenantSchema);
        mpaasQuery.update("field_name", field.getFieldName());
        mpaasQuery.eq("id", field.getId());
        mpaasQuery.table("apaas_data_model_field");
        mpaasQuery.doUpdate(DataModelField.class);
    }


    public void insertField(DataModelField field) {
        if (field == null) {
            return;
        }
        MpaasQuery mpaasQuery = runtimeDatasourceService.buildTenantMpaasQuery(tenantSchema);
        MpaasQuery id = mpaasQuery.eq("id", field.getId());
        if(id != null){
            mpaasQuery.table("apaas_data_model_field");
            mpaasQuery.doUpdate(field);
        }
        else{
            mpaasQuery.table("apaas_data_model_field");
            mpaasQuery.doInsert(field);
        }
    }
}
